package com.fak.wid;

import java.io.IOException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.fak.wid.DBAdapter.DatabaseHelper;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class widget_small extends AppWidgetProvider {
	public static String TAG="Widget";
	public static String ACTION_WIDGET_FAVORIT = "FavoritWidget";	
	public static String ACTION_WIDGET_OPTIONS_SMALL = "OptionsWidget";
	public static boolean ACTION_WIDGET_PREFERENCES_SMALL;
	public static String quote_small = "";
	public static DBAdapter db_small;
	public static String ddd_small ="";
	public static String uri="";
	public static Context con_small;
	public static int time =300000;
	private PendingIntent pendingIntentService_small;
	private  String ListPreference_small;
	private Thread u_small;
	private Runnable updater_small;
	
 	public void onUpdate(final Context context, AppWidgetManager appWidgetManager,
	        int[] appWidgetIds) {
 		
 		
 		
        con_small = context;
     
 		 DatabaseHelper myDbHelper = new DatabaseHelper(context);
 	    

 	     try {
 	     	myDbHelper.createDataBase();
 	     	Log.d(TAG,"copy done succesfful");
 	     	myDbHelper.close();

 		} catch (IOException ioe) {
 			Log.d(TAG,"ERROR copiring");}
		
        
 		
    	
         
 		
		RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.widget_small);
        Intent service = new Intent(context, UpdateService_small.class);
        pendingIntentService_small = PendingIntent.getService(context, 0, service, 0);
       // views.setOnClickPendingIntent(R.id.imageView1_small, pendingIntentService_small);
        
        Intent servicefavorit = new Intent(context, FavoritService_small.class);
        PendingIntent pendingIntentServiceFavorit = PendingIntent.getService(context, 0, servicefavorit, 0);
        views.setOnClickPendingIntent(R.id.imageView1_small, pendingIntentServiceFavorit);
        
        
        
        Intent favoritIntent = new Intent(context, favorit.class);
        favoritIntent.setAction(ACTION_WIDGET_FAVORIT);
        PendingIntent favoritPendingIntent = PendingIntent.getActivity(context, 0, favoritIntent, 0);
        views.setOnClickPendingIntent(R.id.button1_small, favoritPendingIntent);
        appWidgetManager.updateAppWidget(appWidgetIds, views);
        
        
        
        
         updater_small = new Runnable(){
        	public boolean stopped = false;
    		public void run() {
    			 try {
    	                while (!stopped) {

    	                	pendingIntentService_small.send();
    	                    try {
    	                    	 SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
    	                    	 ListPreference_small = settings.getString("listPreftime", "1");
    	                    	 if(ListPreference_small.equals("0.1")){
    	                         	 time = 60000;
    	 						};
    	 						if(ListPreference_small.equals("0.3")){
    	 							time = 180000;
    	 						};
    	                    	  if(ListPreference_small.equals("1")){
    	                         	 time = 300000;
    	 						};
    	 						if(ListPreference_small.equals("2")){
    	 							time = 900000;
    	 						};
    	 						if(ListPreference_small.equals("3")){
    	 							time = 1800000;
    	 						};
    	 						if(ListPreference_small.equals("4")){
    	 							time = 3600000;
    	 						};
    	 						if(ListPreference_small.equals("5")){
    	 							time = 7200000;
    	 						};
    	                         if(ListPreference_small.equals("6")){
    	                         	time = 14400000;
    	 						};
    	                         if(ListPreference_small.equals("7")){
    	                         	time = 28800000;
    	 						};
    	                    	
    	                        Thread.sleep(time);
    	                        Log.i("time", "w="+time);
    	                    } catch (Exception e) {
    	                    }
    	                }
    	            } catch (Exception e) {
    	            }
    			
    		}
        };
        
        
        u_small = new Thread(updater_small);
         u_small.start();
		
         
         
         
         
         
	    }
 	
 	
 	
 	
 	
 	
 	
 	//------------------------------------------
 	@Override
 	public void onDeleted(final Context ctxt, int[] ids)
	{
 		
		new Thread(new Runnable(){
			public void run() {
				System.exit(0);
			
			}
		}).start();
	}
 	//-------------------------------------------------------------
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
	public static String Online()
    {
		String quote_online;
		Document doc = null;
		try {
		URL url = new URL(uri);
		        
		           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		           DocumentBuilder db = dbf.newDocumentBuilder();
		           doc = db.parse(new InputSource(url.openStream()));
		NodeList list = doc.getElementsByTagName("quoteText");
		NodeList list1 = doc.getElementsByTagName("quoteAuthor");
		int i = 0;
		        Node n= list.item(i);
		        Node n1= list1.item(i);
		        
		        String quote  = n.getFirstChild().getNodeValue();
		      String author  = n1.getFirstChild().getNodeValue();
		   quote_online = quote+"\n"+author;
		} catch (Exception ioe) {
	    
			quote_online = "Îøèáêà ïðè ïîäêëþ÷åíèè";
			
	}
	     return quote_online; 
	    
	 }
	
	
	
	public static RemoteViews textupdate(Context context) {
		String ListPreferenceLang="";
     	
     	 SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
 		ListPreferenceLang = settings.getString("listPrefLang", "1");
 		
     	 RemoteViews updateViews = null;
     	 updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_small);
     	 final DBAdapter db = new DBAdapter(context);	
     	
     	
 		
 		if( ListPreferenceLang.equals("1")){
 			uri = "http://api.forismatic.com/api/1.0/?method=getQuote&format=xml&lang=ru";
 			
 		}else{
 			uri = "http://api.forismatic.com/api/1.0/?method=getQuote&format=xml&lang=en";
 		   
 		}
		
        if (settings.getBoolean("checkboxPref",false)) {
        	
     		String dd = Online();
     		quote_small=dd;
     	
       	
     	} else {
     		
     		 db.open();
        	 quote_small = db.getRandomEntry();  
        	db.close();
     	 
    	}
        
        
        
        
        updateViews.setTextViewText(R.id.testtext_small, quote_small);
			return updateViews;	
     }
	 
	    public static class UpdateService_small extends Service {
	        @Override
	        public void onStart(Intent intent, int startId) {
	        	 // TODO Auto-generated method stub 
	        	  super.onStart(intent, startId);
	        	 
	        	  RemoteViews updateViews = textupdate(this);
	        	ComponentName thisWidget = new ComponentName(this, widget_small.class);
	            AppWidgetManager manager = AppWidgetManager.getInstance(this);
	            manager.updateAppWidget(thisWidget, updateViews);
	        }
	    	@Override
			public IBinder onBind(Intent arg0) {
				// TODO Auto-generated method stub
				return null;
			}
	    }
	    
	    
	    public static RemoteViews textadd(Context context) {
	     	 
	     	 RemoteViews favoritViews = null;
	     	favoritViews = new RemoteViews(context.getPackageName(), R.id.imageView1_small);
	     	  DBAdapter db = new DBAdapter(context);	
	     	 SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
	     	 db.open();
	     	if(quote_small.equalsIgnoreCase("Îøèáêà ïðè ïîäêëþ÷åíèè")){
	        	
	        	
	        	 
	     		Toast.makeText(context, "Îøèáêà", Toast.LENGTH_LONG).show();
	        }else{
	        	db.insertFavoritQuote(quote_small.toString());
		     	
	        	Toast.makeText(context, "Öèòàòà äîáàâëåíà!", Toast.LENGTH_LONG).show();
	        }
	     	
	     	db.close();
	     	
	     	return favoritViews;
	     }
	    public static class FavoritService_small extends Service {
	        @Override
	        public void onStart(Intent intent, int startId) {
	        	RemoteViews favoritViews = textadd(this);
	            }
	    	@Override
			public IBinder onBind(Intent arg0) {
				// TODO Auto-generated method stub
				return null;
			}
	    }
	   
	    
	
	
	
}